package net.forsuber.data;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Data provider for www.perfectgonzo.com flash video sourceFile.
 * <p/>
 * User: lzap
 * Date: 25.7.2007
 * Time: 21:32:53
 */

public class PerfectgonzoFileDataSource implements DataSource {

    private static final Log LOG = LogFactory.getLog(PerfectgonzoFileDataSource.class);

    private File sourceFile;

    private ArrayList<String[]> lines = new ArrayList<String[]>();

    public File getSourceFile() {
        return sourceFile;
    }

    public void setSourceFile(File sourceFile) {
        this.sourceFile = sourceFile;
    }

    public void open() throws DataSourceException {
        try {
            LOG.info("Opening data source file " + sourceFile.getAbsolutePath());
            String line;
            BufferedReader reader = new BufferedReader(new FileReader(sourceFile));
            while ((line = reader.readLine()) != null) {
                lines.add(line.split("\\|"));
            }
            reader.close();
            LOG.info("Records read: " + lines.size());
        } catch (IOException e) {
            throw new DataSourceException(e);
        }
    }

    public int size() {
        return lines.size();
    }

    private String get(int row, int column) {
        try {
            return lines.get(lines.size() - row - 1)[column];
        } catch (ArrayIndexOutOfBoundsException e) {
            return null;
        }
    }

    public Record getRecord(final int index) {
        if (index < 0 || index >= lines.size())
            return null;
        else
            return new Record() {

                public String getTitle() {
                    return get(index, 2) + " at " + get(index, 0) + " flash video";
                }

                public String getBody() {
                    return get(index, 6);
                }

                public String[] getAadditional() {
                    return new String[]{get(index, 2).toLowerCase(), get(index, 0).toLowerCase()};
                }
            };
    }

    public void close() throws DataSourceException {
        // nop
    }
}
